<template>
  <el-dialog v-model="dialogVisible" :title="title" width="50%" draggable :before-close="handleBeforeClose">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" size="default">
      <el-row :gutter="20">
        <!-- 账户编号 -->
        <el-col :span="11">
          <el-form-item label="账户编号" prop="accountNo">
            <el-input v-model="formData.accountNo" placeholder="账户编号将自动生成" disabled />
          </el-form-item>
        </el-col>

        <!-- 账户名称 -->
        <el-col :span="11">
          <el-form-item label="账户名称" prop="accountName">
            <el-input v-model="formData.accountName" placeholder="请输入账户名称" />
          </el-form-item>
        </el-col>

        <!-- 设为默认 -->
        <!-- <el-col :span="2">
          <el-form-item>
            <el-checkbox v-model="formData.isDefault" label="设为默认" />
          </el-form-item>
        </el-col> -->

        <!-- 余额日期 -->
        <el-col :span="11">
          <el-form-item label="余额日期" prop="setupDate">
            <el-date-picker v-model="formData.setupDate" type="date" placeholder="选择日期" format="YYYY-MM-DD"
              value-format="YYYY-MM-DD" style="width: 100%" />
          </el-form-item>
        </el-col>

        <!-- 期初余额 -->
        <el-col :span="13">
          <el-form-item label="期初余额" prop="initialBalance">
            <el-input 
              v-model.number="formData.initialBalance" 
              placeholder="请输入期初余额" 
              type="number" 
              :precision="2"
              :step="0.01" 
              style="width: 100%" 
              :disabled="!isAddMode"  
            />
          </el-form-item>
        </el-col>

        <!-- 账户类别 -->
        <el-col :span="11">
          <el-form-item label="账户类别" prop="accountType">
            <el-select v-model="formData.accountType" placeholder="请选择账户类别" style="width: 100%">
              <el-option label="现金" value="现金" />
              <el-option label="银行存款" value="银行存款" />
              <el-option label="支付宝" value="支付宝" />
              <el-option label="微信支付" value="微信支付" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, defineProps, defineEmits } from 'vue';
import { ElMessage } from 'element-plus';

// 定义props
const props = defineProps({
  // 控制对话框显示/隐藏
  visible: {
    type: Boolean,
    default: false
  },
  // 账户数据（编辑时传入）
  accountData: {
    type: Object,
    default: () => ({})
  },
  // 对话框标题
  title: {
    type: String,
    default: '修改结算账户'
  },
  // 是否为新增模式
  isAddMode: {
    type: Boolean,
    default: false
  }
});

// 定义事件
const emit = defineEmits([
  'update:visible', // 用于双向绑定
  'submit',         // 提交事件
  'cancel'          // 取消事件
]);

// 表单引用
const formRef = ref(null);

// 对话框显示状态
const dialogVisible = ref(false);

// 表单数据
const formData = reactive({
  accountNo: '',
  accountName: '',
  isDefault: false,
  setupDate: '',
  initialBalance: 0,
  accountType: ''
});

// 表单验证规则
const formRules = reactive({
  accountName: [
    { required: true, message: '请输入账户名称', trigger: 'blur' },
    { min: 2, max: 50, message: '账户名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  initialBalance: [
    { required: true, message: '请输入期初余额', trigger: 'blur' },
    { type: 'number', message: '期初余额必须是数字', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value < 0) {
          callback(new Error('期初余额不能为负数'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  accountType: [
    { required: true, message: '请选择账户类别', trigger: 'change' }
  ],
  setupDate: [
    { required: true, message: '请选择余额日期', trigger: 'change' }
  ]
});

// 初始化表单数据
const initFormData = (data) => {
  Object.assign(formData, {
    accountNo: data.accountNo || '',
    accountName: data.accountName || '',
    isDefault: data.isDefault || false,
    setupDate: data.setupDate || new Date().toISOString().split('T')[0],
    initialBalance: data.initialBalance || 0,
    accountType: data.accountType || ''
  });
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  initFormData({});
};

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    const valid = await formRef.value.validate();
    if (!valid) return;

    // 触发提交事件
    emit('submit', { ...formData });

    // 关闭对话框
    dialogVisible.value = false;

  } catch (error) {
    console.error('表单验证失败:', error);
    ElMessage.error('请检查表单数据');
  }
};

// 取消操作
const handleCancel = () => {
  // 触发取消事件
  emit('cancel');

  // 关闭对话框
  dialogVisible.value = false;
};

// 对话框关闭前的回调
const handleBeforeClose = (done) => {
  // 可以在这里添加关闭前的确认逻辑，例如表单有修改时提示用户确认
  done();
};

// 监听props.visible变化，更新内部状态
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal;

  // 当对话框显示时，初始化表单数据
  if (newVal) {
    initFormData(props.accountData);
  }
});

// 监听内部dialogVisible变化，同步到父组件
watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal);

  // 对话框关闭时重置表单
  if (!newVal) {
    resetForm();
  }
});
</script>

<style scoped>
/* 调整表单布局 */
.el-form-item {
  margin-bottom: 18px;
}

.el-date-editor {
  width: 100%;
}

.el-col .el-form-item {
  margin-bottom: 0;
  display: flex;
  align-items: flex-end;
  margin-top: 10px
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-input-number .el-input__inner) {
  text-align: right;
}
</style>